package com.example.fan.airline_reservation.fragment_class;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.fan.airline_reservation.AC_Interface;
import com.example.fan.airline_reservation.Model.Fight;
import com.example.fan.airline_reservation.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

public class ac_add_fights extends Fragment implements View.OnClickListener, DatePickerDialog.OnDateSetListener,
        TimePickerDialog.OnTimeSetListener{

    TextView YMDChoose;/*选择出发年月日的TextView*/
    TextView MSChoose;/*选择出发时间的TextView*/
    TextView toYMDChoose;/*选择到达年月日的TextView*/
    TextView toMSChoose;/*选择到达时间的TextView*/
    Button submit;/*上传航班信息的按钮*/
    int year,month,day,hour,min;/*出发年月日时分*/
    int year1,month1,day1,hour1,min1;/*到达年月日时分*/
    EditText fight,from,fromAirport,to,toAirport,price;
    Spinner sp;/*飞机型号下拉控件*/
    Date date;/*出发时间*/
    Date todate;/*到达时间*/
    String sfight,smodel,sfrom,sfromName,sto,stoName;
    double sprice;
    boolean isdeparture=false;

    /*碎片动态加载场景*/
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.activity_ac_add_fights,
                container,false);

        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        /*云端数据库连接*/
        Bmob.initialize(getActivity(), "0802cbf346296dc9fac5a477f911ba39");

        YMDChoose=(TextView)getActivity().findViewById(R.id.YMDChoose);
        YMDChoose.setOnClickListener(this);
        MSChoose=(TextView)getActivity().findViewById(R.id.MSChoose);
        MSChoose.setOnClickListener(this);

        toYMDChoose=(TextView)getActivity().findViewById(R.id.toYMDChoose);
        toYMDChoose.setOnClickListener(this);
        toMSChoose=(TextView)getActivity().findViewById(R.id.toMSChoose);
        toMSChoose.setOnClickListener(this);

        submit=(Button)getActivity().findViewById(R.id.submit);
        submit.setOnClickListener(this);

        /*下拉选择飞机型号的代码*/
        sp=(Spinner)getActivity().findViewById(R.id.model);
        smodel=(String) sp.getSelectedItem();
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            /*选中下拉菜单事件*/
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                smodel=(String) sp.getSelectedItem();
                Log.d("test",smodel);
            }
            /*没有选中事件*/
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        /*获取航班号，出发地，目的地，价格的控件*/
        fight=(EditText)getActivity().findViewById(R.id.fight);
        from=(EditText)getActivity().findViewById(R.id.from);
        fromAirport=(EditText)getActivity().findViewById(R.id.fromAirport);
        to=(EditText)getActivity().findViewById(R.id.to);
        toAirport=(EditText)getActivity().findViewById(R.id.toAirport);
        price=(EditText)getActivity().findViewById(R.id.price);
    }

    /*选择年月日的操作*/
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        if(isdeparture==true) {
            String desc = String.format("%d年%d月%d日", year, month + 1, dayOfMonth);
            this.year = year;
            this.month = month + 1;
            this.day = dayOfMonth;
            Log.d("test", String.valueOf(year));
            YMDChoose.setText(desc);
        }else{
            String desc = String.format("%d年%d月%d日", year, month + 1, dayOfMonth);
            this.year1 = year;
            this.month1 = month + 1;
            this.day1 = dayOfMonth;
            Log.d("test", String.valueOf(year));
            toYMDChoose.setText(desc);
        }
    }
    /*选择分秒的操作*/
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        if (isdeparture==true) {
            String desc = String.format("%d时%d分", hourOfDay, minute);
            this.hour = hourOfDay;
            this.min = minute;
            MSChoose.setText(desc);
        }else {
            String desc = String.format("%d时%d分", hourOfDay, minute);
            this.hour1 = hourOfDay;
            this.min1 = minute;
            toMSChoose.setText(desc);
        }
    }

    /*点击事件*/
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            /*出发时间*/
            case R.id.YMDChoose: {
                    isdeparture=true;
                    Calendar calendar=Calendar.getInstance();
                    DatePickerDialog dialog = new DatePickerDialog(getActivity(),this,
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH));
                    dialog.show();
                }
                break;
            case R.id.MSChoose: {
                    isdeparture=true;
                    Calendar calendar=Calendar.getInstance();
                    TimePickerDialog dialog=new TimePickerDialog(getActivity(),this,
                        calendar.get(Calendar.HOUR_OF_DAY),
                        calendar.get(Calendar.MINUTE),
                        true);
                    dialog.show(); }
                break;

            /*到达时间*/
            case R.id.toYMDChoose: {
                isdeparture=false;
                Calendar calendar=Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(getActivity(),this,
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH));
                dialog.show(); }
            break;
            case R.id.toMSChoose: {
                isdeparture=false;
                Calendar calendar=Calendar.getInstance();
                TimePickerDialog dialog=new TimePickerDialog(getActivity(),this,
                        calendar.get(Calendar.HOUR_OF_DAY),
                        calendar.get(Calendar.MINUTE),
                        true);
                dialog.show(); }
            break;

            /*提交*/
            case R.id.submit:
                date=new Date(year-1900,month-1,day,hour,min);
                todate=new Date(year1-1900,month1-1,day1,hour1,min1);
                sfight=fight.getText().toString();
                sfrom=from.getText().toString();
                sfromName=fromAirport.getText().toString();
                sto=to.getText().toString();
                stoName=toAirport.getText().toString();
                try {
                    sprice=Double.valueOf(price.getText().toString());
                }catch (Exception e){
                    sprice=0;
                }

                if (sfight.length()!=0 && sfrom.length()!=0 && sfromName.length()!=0
                        && sto.length()!=0 && stoName.length()!=0 && sprice>0
                        && date.getTime()<todate.getTime()) {

                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String ff = format.format(date);
                    String tt = format.format(todate);
                    String str = "航班号:" + sfight +
                            "\n飞机型号:" + smodel +
                            "\n出发时间:" + ff +
                            "\n出发地:" + sfrom + " " + sfromName +
                            "\n到达时间:" + tt +
                            "\n目的地:" + sto + " " + stoName +
                            "\n票价:" + sprice;


                    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                    dialog.setTitle("请你确认你的提交信息");
                    dialog.setMessage(str);
                    dialog.setCancelable(false);
                    dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            final Fight f = new Fight(sfight, smodel, date, sfrom, sfromName, sto, stoName, sprice, todate, 0, 0, 0);
                            f.save(new SaveListener<String>() {
                                @Override
                                public void done(String s, BmobException e) {
                                    if (e == null) {
                                        ToastShow("添加航班信息成功！");
                                    } else {
                                        ToastShow("错误码：" + e.getErrorCode() + "，错误描述：" + e.getMessage());
                                    }
                                }
                            });
                        }
                    });
                    dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    dialog.show();
                }else {
                    ToastShow("请确认您输入的航班信息是否正确");
                }
                break;
        }
    }

    /*格式化日期数据*/
    /*获得年月日的办法，其中年要+1900，月要+1*/
    /*Log.d("test", String.valueOf(date.getYear()+1900));
      Log.d("test", String.valueOf(date.getMonth()+1));
      Log.d("test", String.valueOf(date.getDate()));
      Log.d("test", String.valueOf(date.getHours()));
      Log.d("test", String.valueOf(date.getMinutes()));*/

    public void ToastShow(String str){
        Toast.makeText(getActivity(),str,Toast.LENGTH_LONG).show();
    }
}
